package org.grow.took.Controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.grow.took.dao.PlayerDao;
import org.grow.took.entity.PagedResults;
import org.grow.took.entity.Player;
import org.grow.took.entity.PlayerQueryCondition;
import org.grow.took.entity.PlayerSearchForm;
import org.grow.took.exception.SeptemberException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Random;

@RestController
@RequestMapping("/ceto/player")

public class PlayerController {
    @Autowired
    private PlayerDao playerDao;

    /*
    *@RequestBody主要用来接收前端传递给后端的json字符串中的数据的(请求体中的数据的)；
    * 而最常用的使用请求体传参的无疑是POST请求了，所以使用@RequestBody接收数据时，一般都用POST方式进行提交。
     */
    @PostMapping("/query")
    public PagedResults<Player> query(@RequestBody PlayerSearchForm playerSearchForm){
        Integer pageNum = playerSearchForm.getPageNum();
//        if (pageNum<=0){
//            throw new RuntimeException();//下面的代码都不会运行
//        }
        if (pageNum<=0){
            throw new SeptemberException("抱歉，查看页数至少为一页");
        }
        Integer pageSize = playerSearchForm.getPageSize();
        PlayerQueryCondition queryCondition = playerSearchForm.getQueryCondition();
        IPage<Player> page = new Page(pageNum, pageSize);
        //playerDao.dynamicQuery(queryCondition);
        IPage<Player> playerIPage = playerDao.dynamicQuery(page, queryCondition);
        List<Player> records = playerIPage.getRecords();
        long total = playerIPage.getTotal();
        PagedResults<Player> pagedResults = new PagedResults();
        pagedResults.setResults(records);
        pagedResults.setTotal(total);
        return pagedResults;
        //return null;
    }

    @Autowired
    private Random random;
   @PostMapping("/insert")
   //@ResponseBody，将对象转换为可以在网络上传输的字符串
   public Player insert(@RequestBody Player player){
       System.out.println(player);
       //入库的数据：1.前端传入的数据并且值得信任（前端数据校验，后端也需要进行数据校验
       //年学院编号，自增长的随机数来表示
       //Random线程安全，性能一般
       //Random random = new Random();
       int k=random.nextInt(8999)+1000;//0~9000取一个随机数，加上1000则是1000~
       player.setPlayerCode("811"+k);
       player.setVersion(0);
       //前端传入但不值得信赖的数据：
       player.setPlayerId(0);//不管前端传入什么，都设置为0，方便数据库自增
       playerDao.insert(player);
       return player;
   }




}
